/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.cloud.feign.decoder;

import com.iwindplus.boot.util.CryptoUtil;
import com.iwindplus.boot.web.domain.property.ResponseBodyProperty;
import com.iwindplus.boot.web.domain.property.ResponseBodyProperty.ResponseBodyCryptoConfig;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import lombok.extern.slf4j.Slf4j;

/**
 * feign统一响应解码器.
 *
 * @author zengdegui
 * @since 2024/06/18 20:15
 */
@Slf4j
public record FeignResponseDecoder(Decoder decoder, ResponseBodyProperty responseBodyProperty) implements Decoder {

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        // 读取响应体并解密
        final ResponseBodyCryptoConfig crypto = responseBodyProperty.getCrypto();
        if (Boolean.TRUE.equals(responseBodyProperty.getEnabled()) && Boolean.TRUE.equals(crypto.getEnabled())) {
            log.info("feign调用，解密响应体数据，算法={}",  crypto.getAlgorithm());

            String text = Util.toString(response.body().asReader(Charset.defaultCharset()));
            final String decryptedData = CryptoUtil.decrypt(text, crypto);
            response = Response.builder()
                .status(response.status())
                .request(response.request())
                .headers(response.headers())
                .reason(response.reason())
                .body(decryptedData, Charset.defaultCharset())
                .protocolVersion(response.protocolVersion())
                .build();
        }
        return this.decoder.decode(response, type);
    }
}
